<template>
  <div v-if="mode === 'read'" class="read-text">
    <span class="text">{{ formatter(curBizObject[card.cardCode]) }}</span>
  </div>
  <a-input-number
    v-else
    class="card-input-number"
    v-model:value="val"
    :formatter="(value) => formatter(value)"
    :parser="(value) => value.replace(/\s?[,%]*/g, '')"
  />
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';
import { FormatNumberValue } from '@/global/util/common';

export default defineComponent({
  name: 'CardInputNumber',
  props: {
    mode: {
      type: String,
      default: '',
    },
    card: {
      type: Object as any,
      default: () => ({}),
    },
    curBizObject: {
      type: Object as any,
      default: () => ({}),
    },
  },
  setup(props, context) {
    const ctlValue = computed(() => props.card.controls.ctlValue);
    const dataFormat = computed(() => props.card.controls.dataFormat);
    const { decimals, isShowDecimal, isShowThousand, type } =
      dataFormat.value.defaultValue;
    const formatter = (val: number) => {
      return FormatNumberValue(
        isShowDecimal,
        isShowThousand,
        decimals,
        val,
        type,
      );
    };
    const parser = (val: string) => {
      if (type === 'data') {
        return val.replace(/\s?|(,*)/g, '');
      } else {
        if (isShowDecimal) {
          return Number(val.replace(/%/g, '')).toFixed(decimals);
        }
        return Number(val.replace(/%/g, '')).toFixed(0);
      }
    };
    const val = computed({
      get: () => ctlValue.value.value ?? ctlValue.value.defaultValue,
      set: (val) => {
        context.emit('updateValue', val, 'value', props.card.controls.ctlValue);
      },
    });
    return {
      val,
      formatter,
      parser,
    };
  },
});
</script>

<style lang="less" scoped>
.card-input-number {
  width: 100%;
  font-size: 12px;
  line-height: 22px;
  border-radius: 4px;
}
.read-text {
  padding: 6px 12px;
  background-color: @rb-background-color;
  .text {
    display: inline-block;
    line-height: 22px;
  }
}
</style>
